//防抖
function debounce(func, wait, immdediate) {
    let result = null,
        timeout = null;
    return function (...arg) {
        //debounce里的this是func里要用到的 所以先存起来
        //跟bind预处理类似
        let context = this,
            now = immdediate && !timeout;
        //只有设置了立即执行,且没外另外的延时器在执行时才为true
        clearTimeout(timeout); //=>重要:在设置新的定时器之前,我们要把之前设置的定时器都干掉,因为防抖的目的是等待时间内,只执行一次
        timeout = setTimeout(() => {
            //如果设置了立即执行,就不在定时器里延时执行了
            if (!immdediate) result = func.call(context, ...arg);
            clearTimeout(timeout);
            timeout = null;
        }, wait)
        //相对上面,now为true则不走定时器,直接执行func
        if (now) result = func.call(context, ...arg);
        return result;
    }
}


//search
$(function () {
    //搜索框聚焦显示热点,失去焦点隐藏热点
    $('.text').on('focus', function () {
        $('.hots').css('display', 'block')
    }).on('blur', function () {
        /**
        //点击热点条目,搜索框显示条目内容
        $('.hots>dl').on('click', 'dd', function (e) {
            console.log(e.target);
            $('.hots').css('display', 'none')
        })
         */
        $('.hots').css('display', 'none')
    });
});

//全部商品移入显示NAV 移除隐藏NAV
$(function () {
    $('.categorynav').on('mouseenter', function () {
        $('.category').stop().slideDown();
        $('.categorynav>a').css('color', '#cb242b');
    }).on('mouseleave', function () {
        $('.category').stop().slideUp();
        $('.categorynav>a').css('color', '#3a3a3a');
    })
});

//放大镜

$(function () {
    let $btnl = $('.back');
    let $btnr = $('.forward');
    let $sImgbox = $('.smallimges');
    let $sImgLength = $('.smallimges>li').length;
    let sNum = 0;
    let $bigImg = $('.bigimg');
    let $midImg = $('.midimg');
    let $mid = $('.mid');
    let $zoom = $('.zoom');
    let $big = $('.big');

    //左右点击按钮
    $btnr.on('click', function () {
        sNum++;
        sNum = sNum >= $sImgLength - 5 ? $sImgLength - 5 : sNum;

        $sImgbox.animate({
            left: -74 * sNum
        })
    });
    $btnl.on('click', function () {
        sNum--;
        sNum = sNum <= 0 ? 0 : sNum;
        $sImgbox.animate({
            left: -74 * sNum
        })
    });
    //smallimges移入切换图片效果
    $sImgbox.on('mouseover', 'li', function (e) {
        if (e.target.nodeName === 'IMG') {
            let $sImg = $(e.target);
            console.log();
            $sImg.parent().css('border', '1px solid #ca141d').siblings().css('border', '1px solid transparent');
            $bigImg.attr('src', $sImg.attr('data-src'));
            $midImg.attr('src', $sImg.attr('data-src'));
        }
    })


    //移动方法
    function move(e) {
        $big.show();
        let disX = e.pageX - $mid.offset().left - $zoom.width() / 2;
        let disY = e.pageY - $mid.offset().top - $zoom.height() / 2;
        disX = disX <= 0 ? 0 : disX;
        disY = disY <= 0 ? 0 : disY;
        disX = disX >= $mid.width() - $zoom.width() ? $mid.width() - $zoom.width() : disX;
        disY = disY >= $mid.height() - $zoom.height() ? $mid.height() - $zoom.height() : disY;
        $zoom.css({
            left: disX,
            top: disY,
            opacity: 1
        });
        $bigImg.css({
            left: -disX * (800 / 450),
            top: -disY * (800 / 450)
        })
    }
    //zoom移动效果
    $mid.on('mouseenter', function () {
        $(document).on('mousemove', move);
    }).on('mouseout', function () {
        // $zoom.stop().animate({
        //     opacity: 0
        // }, 200);
        $zoom.css({
            opacity: 0
        });
        $big.hide();
        $(document).off('mousemove', move);
    })

    //整个放大镜跟随滚轮移动效果
    // $(document).on('scroll', _.debounce(fn,0));
    // function fn() {
    //     let mtop = parseInt($('.left').offset().top);
    //     let scrT = parseInt($('body,html').scrollTop());
    //     // console.log($('body,html').scrollTop());
    //     // console.log(scrT);
    //     if (scrT >= mtop) {
    //         let num = scrT - mtop+20;
    //         console.log(num);
    //         $('.left').css('top', num)
    //     }
    // }
});


//detail 右边的一些点击效果
$(function () {
    //block点击带边框
    $('.block').on('click', function () {
        $(this).addClass('active').siblings().removeClass('active');
    })

    //点击切换手机颜色
    $('.changewhite').on('click', function () {
        $('.smallimges>li').each(function (i, ele) {
            let tarImg = $(ele).find('img');
            console.log(tarImg.attr('src'));
            console.log(tarImg.attr('data-src'));
            tarImg.attr({
                'src': `./img/magnifier/small${i+1}.png`,
                'data-src': `./img/magnifier/big${i+1}.png`
            });
            $('.midimg').attr('src', './img/magnifier/big1.png');
            $('.bigimg').attr('src', './img/magnifier/big1.png');
            // ./img/magnifier/small1.png
            // ./img/magnifier/big1.png
            // ./img/magnifier/small2.png
            // ./img/magnifier/big2.png
        });
    });
    $('.changeblack').on('click', function () {
        $('.smallimges>li').each(function (i, ele) {
            let tarImg = $(ele).find('img');
            console.log(tarImg.attr('src'));
            console.log(tarImg.attr('data-src'));
            tarImg.attr({
                'src': `./img/magnifier/bs${i+1}.png`,
                'data-src': `./img/magnifier/bb${i+1}.png`
            });
            $('.midimg').attr('src', './img/magnifier/bb1.png');
            $('.bigimg').attr('src', './img/magnifier/bb1.png');
        });
    });

    //购物车加减点击
    let shopNum = 1;
    $('.plus').on('click', function () {
        shopNum++;
        shopNum = shopNum >= 10 ? 10 : shopNum;
        $('.msg').html(shopNum);
    });
    $('.minus').on('click', function () {
        shopNum--;
        shopNum = shopNum <= 1 ? 1 : shopNum;
        $('.msg').html(shopNum);
    })
});


//finalnav TAB栏切换 
$(function () {
    let $bar = $('.bar');
    let top = parseInt($bar.offset().top);
    //bar的点击 楼层跳转事件
    $('.bar>li').on('click', function (e) {
        $(this).addClass('current').siblings().removeClass('current');
        let $index = $(this).index();
        let sum = 0;
        let $prevLi = $(this).prevAll('li');
        //点击时获取当前点击LI的之前LI
        //因为bar LI的个数与 内容OL  LI的个数一样
        //遍历preLi 获取ol中的LI 将各个可遍历到的ol中的LI的高度加起来
        //总和sum 加上固定的980就是楼层高度 
        //(其实980就是bar到顶部的距离)
        $prevLi.each((i) => {
            sum += $('.kindpic>ol>li').eq(i).height();
        });
        $('html,body').animate({
            scrollTop: 980 + sum
        })
    });
    $(document).on('scroll', function () {
        let sTop = parseInt($('html,bady').scrollTop());
        if (sTop >= (top + $bar.height() + 20)) {
            $bar.css({
                'position': 'fixed'
            });
            let olList = document.querySelectorAll('.kindpic>ol>li');
            let ind = null;
            let olHeight = top;
            [...olList].findIndex((ele, i) => {
                // olHeight += $(ele).height();
                // console.log(sTop >= olHeight);
                if (sTop > olHeight) {
                    olHeight += $(ele).height();
                    ind = i;
                };
                $('.bar>li').eq(ind).addClass('current').siblings().removeClass('current');
            });
            console.log(olHeight);

        } else {
            $bar.css({
                'position': 'static'
            })
        }
    })
});


//回到顶部
//fixnav 固定导航栏(包括回到顶部及楼层)
$(function () {
    let flag = true;

    $(window).on('scroll', _.debounce(function () {
        let $this = $(this);
        let cilentH = $(window).height();
        if ($this.scrollTop() > cilentH && flag === true) {
            $('.fixnav').append(`<div class="shop gotop">
                                    <i class="iconfont">&#xe76c;</i>
                                    <p>回到顶部</p>
                                 </div>`);
            $('.gotop').on('click', function () {
                //点击移除楼层 移除回到顶部
                $('.fixnav').find($('.gotop')).remove();
                $("html,body").stop().animate({
                    scrollTop: 0
                });
                return false;
            });
            flag = false;
        }
        if ($this.scrollTop() <= cilentH) {
            $('.fixnav').find($('.gotop')).remove();
            flag = true;
        }
    }, 100, true));

})

//加入购物车的跳转
$(function () {
    $('.addcart').children('p').eq(1).on('click', function () {
        location = './shopcart.html';
    });
    $('.addcart').children('p').eq(0).on('click', function () {
        layer.msg('加入购物车成功');

    });
});

//如果登录过显示用户名
$(function () {
    let $ul = $('.hr>ul');
    let $signedin = $('.signedin');
    if (window.localStorage.userinfo) {
        let username = JSON.parse(window.localStorage.userinfo)[0].u_name;
        $signedin.remove();
        $ul.prepend(`
        <li class="quit">
            <a href="javascript:;">${username} </a>
            <a href="javascript:;"> 退出</a>
        </li>
        `);
        $('.quit').children().eq(1).on('click', function () {
            layer.msg('已退出登录');
            localStorage.removeItem('userinfo');
            $(this).parent().parent().prepend(`
            <li class="signedin">
                <a href="./login.html">请登录 </a>
                <a href="./register.html"> 注册</a>
            </li>
            `);
            $(this).parent().remove();
            console.log($(this).parent().parent());
        })
    };
})